package com.north.light.libpicselect.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.north.light.libpicselect.bean.LibPicMediaCursorInfo;
import com.north.light.libpicselect.bean.LibPicMediaExtraInfo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

/**
 * author:li
 * date:2022/7/2
 * desc:媒体管理类
 */
public class LibMediaInfoUtils implements Serializable {

    /**
     * is content://
     *
     * @param url
     * @return
     */
    public static boolean isContent(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return url.startsWith("content://");
    }

    /**
     * get Local video width or height
     */
    public static LibPicMediaExtraInfo getVideoSize(Context context, String url) {
        LibPicMediaExtraInfo mediaExtraInfo = new LibPicMediaExtraInfo();
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (isContent(url)) {
                retriever.setDataSource(context, Uri.parse(url));
            } else {
                retriever.setDataSource(url);
            }
            String orientation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
            int width, height;
            if (TextUtils.equals("90", orientation) || TextUtils.equals("270", orientation)) {
                height = toInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH), 0);
                width = toInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT), 0);
            } else {
                width = toInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH), 0);
                height = toInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT), 0);
            }
            mediaExtraInfo.setWidth(width);
            mediaExtraInfo.setHeight(height);
            mediaExtraInfo.setDuration(toLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION), 0));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return mediaExtraInfo;
    }


    /**
     * 获取图片参数
     */
    public static LibPicMediaExtraInfo getPicSize(Context context, String path) {
        LibPicMediaExtraInfo mediaExtraInfo = new LibPicMediaExtraInfo();
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            InputStream inputStream;
            if (isContent(path)) {
                inputStream = context.getContentResolver().openInputStream(Uri.parse(path));
            } else {
                inputStream = new FileInputStream(path);
            }
            options.inJustDecodeBounds = true;//这个参数设置为true才有效，
            BitmapFactory.decodeStream(inputStream, null, options);//这里的bitmap是个空
            int outHeight = options.outHeight;
            int outWidth = options.outWidth;
            mediaExtraInfo.setWidth(outWidth);
            mediaExtraInfo.setHeight(outHeight);
            inputStream.close();
            return mediaExtraInfo;
        } catch (Exception e) {
            return mediaExtraInfo;
        }
    }

    /**
     * 获取图片参数
     */
    public static LibPicMediaExtraInfo getPicSizeExif(Context context, String path) {
        LibPicMediaExtraInfo mediaExtraInfo = new LibPicMediaExtraInfo();
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            int width = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
            int height = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
            if (rotation == ExifInterface.ORIENTATION_ROTATE_90 || rotation == ExifInterface.ORIENTATION_ROTATE_270) {
                // 图片被旋转90或者270，使用时候将width、height换下
                int temp = height;
                height = width;
                width = temp;
            } else {
                // 宽高对应

            }
            mediaExtraInfo.setWidth(width);
            mediaExtraInfo.setHeight(height);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaExtraInfo;
    }


    private static int toInt(Object o, int defaultValue) {
        if (o == null) {
            return defaultValue;
        }
        int value;
        try {
            String s = o.toString().trim();
            if (s.contains(".")) {
                value = Integer.parseInt(s.substring(0, s.lastIndexOf(".")));
            } else {
                value = Integer.parseInt(s);
            }
        } catch (Exception e) {
            value = defaultValue;
        }

        return value;
    }


    public static long toLong(Object o, long defaultValue) {
        if (o == null) {
            return defaultValue;
        }
        long value = 0;
        try {
            String s = o.toString().trim();
            if (s.contains(".")) {
                value = Long.parseLong(s.substring(0, s.lastIndexOf(".")));
            } else {
                value = Long.parseLong(s);
            }
        } catch (Exception e) {
            value = defaultValue;
        }


        return value;
    }


    //通过cursor获取信息--------------------------------------------------------------------
    private static final String DURATION = "duration";
    private static final String[] PROJECTION = {
            MediaStore.Files.FileColumns._ID,
            MediaStore.MediaColumns.DATA,
            MediaStore.MediaColumns.MIME_TYPE,
            MediaStore.MediaColumns.WIDTH,
            MediaStore.MediaColumns.HEIGHT,
            DURATION,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DATE_MODIFIED,
            MediaStore.Images.Media.DISPLAY_NAME};

    /**
     * change by lzt 20220713 duration增加try catch
     * */
    public static LibPicMediaCursorInfo getCursorInfo(Cursor cursor) {
        if (cursor == null) {
            return new LibPicMediaCursorInfo();
        }
        try {
            LibPicMediaCursorInfo result = new LibPicMediaCursorInfo();
            String path = cursor.getString(cursor.getColumnIndexOrThrow(PROJECTION[1]));
            String mediaType = cursor.getString(cursor.getColumnIndexOrThrow(PROJECTION[2]));
            int w = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[3]));
            int h = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[4]));
            try{
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[5]));
                result.setDuration(duration);
            }catch (Exception e){

            }
//            byte[] data = cursor.getBlob(cursor.getColumnIndexOrThrow(PROJECTION[6]));
//            String dataStr = new String(data, 0, data.length - 1);//和path结果一样
            int date = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[7]));
            String displayName = cursor.getString(cursor.getColumnIndexOrThrow(PROJECTION[8]));
            //设置结果
            result.setName(displayName);
            result.setDate(date);
            result.setPath(path);
            result.setFormat(mediaType);
            result.setWidth(w);
            result.setHeight(h);
            return result;
        } catch (Exception e) {
            return new LibPicMediaCursorInfo();
        }
    }


}
